package com.ym.b2b.commons.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/util")
public class UtilController extends BaseController {

    @RequestMapping("load.s")
    public void loads(String fileName, String title, HttpServletRequest request, HttpServletResponse response)
                                                                                                              throws IOException {
        File file = new File(fileName);
        String userAgent = request.getHeader("User-Agent");
        InputStream fis = new BufferedInputStream(new FileInputStream(fileName));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        byte[] bytes = userAgent.contains("MSIE") ? title.getBytes() : title.getBytes("GBK");
        title = new String(bytes, "ISO-8859-1");
        response.addHeader("Content-Disposition", "attachment;filename=" + title);
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }

    @RequestMapping("load.do")
    public void loaddo(String fileName, String title, HttpServletRequest request, HttpServletResponse response)
                                                                                                               throws IOException {
        File file = new File(fileName);
        String userAgent = request.getHeader("User-Agent");
        InputStream fis = new BufferedInputStream(new FileInputStream(fileName));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        byte[] bytes = userAgent.contains("MSIE") ? title.getBytes() : title.getBytes("GBK");
        title = new String(bytes, "ISO-8859-1");
        response.addHeader("Content-Disposition", "attachment;filename=" + title);
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }
}
